<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/26
 * Time: 13:25
 */

namespace app\pay\controller;

use app\common\cachemodel\OrdersLib as OrdersLibCacheModel;
use app\common\cachemodel\privatearea\PrivateAreaMallCompany;
use app\common\cachemodel\privatearea\PrivateAreaOrders;
use app\common\cachemodel\UserAppleNotifyRecord;
use app\common\lib\Orders as OrdersLib;
use app\common\service\ApplePay;
use app\common\service\Orders;
use Exception;
use think\Controller;
use app\common\lib\PayCheckSign;
use think\Log;

/**
 * 支付回调相关接口
 * Class Notify
 * @package app\pay\controller
 */
class Notify extends Controller
{
    protected $config = [
        'APP' => 'wxpay',
        'JSAPI' => ['wxwebpay', 'wx_mini_astro_pay', 'wx_mini_astro_h5_pay'],
        'MWEB' => ['wxwebpay', 'wx_mini_astro_pay'],
    ];

    public function apple()
    {
        $param = $this->request->param();
//        Log::write('苹果回调数据:' . var_export($param, true) . PHP_EOL, 'apple_pay', true);
        $res = ApplePay::getInstance()->validateJwt($param['signedPayload']);
        if ($res)
        {
            $data = json_decode(json_encode($res['data'], true), true);
            if (strtolower($data['environment']) === 'sandbox')
            {
                $GLOBALS['appleNotifySandboxModel'] = true;
            }
            $signedTransactionInfo = ApplePay::getInstance()->validateJwt($data['signedTransactionInfo']);//由 App Store 签名的交易信息
            $originalTransactionId = $signedTransactionInfo['originalTransactionId'];//原始交易ID
            $transactionId = $signedTransactionInfo['transactionId'];//当前交易ID
            $productId = $signedTransactionInfo['productId'];//当前产品ID
            $sub_type = $res['subtype'] ?? '';//标识通知事件的附加信息
            $res['signedTransactionInfoArr'] = $signedTransactionInfo;
//            Log::write('苹果回调数据解析:' . var_export($res, true) . PHP_EOL, 'apple_pay', true);

            $result = (new UserAppleNotifyRecord())->notifyInfo([
                'uuid' => $signedTransactionInfo['appAccountToken'] ?? '',
                'or_trans_id' => $originalTransactionId,
                'trans_id' => $transactionId,
                'product_id' => $productId,
                'notifi_type' => $res['notificationType'],
                'sub_type' => $sub_type,
                'notification_uuid' => $res['notificationUUID'],
                'purchase_date_ms' => $signedTransactionInfo['purchaseDate'],
            ]);
            if ($result)
            {
                return show(200, '', [], 200);
            }
            return show(0, '', [], 500);
        }
        return show(0, '', [], 500);
    }

    /**
     * 微信支付成功以后的回调
     *  <xml>
     *      <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
     *      <attach><![CDATA[支付测试]]></attach>
     *      <bank_type><![CDATA[CFT]]></bank_type>
     *      <fee_type><![CDATA[CNY]]></fee_type>
     *      <is_subscribe><![CDATA[Y]]></is_subscribe>
     *      <mch_id><![CDATA[10000100]]></mch_id>
     *      <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
     *      <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
     *      <out_trade_no><![CDATA[1409811653]]></out_trade_no>
     *      <result_code><![CDATA[SUCCESS]]></result_code>
     *      <return_code><![CDATA[SUCCESS]]></return_code>
     *      <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
     *      <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
     *      <time_end><![CDATA[20140903131540]]></time_end>
     *      <total_fee>1</total_fee><coupon_fee><![CDATA[10]]></coupon_fee>
     *      <coupon_count><![CDATA[1]]></coupon_count>
     *      <coupon_type><![CDATA[CASH]]></coupon_type>
     *      <coupon_id><![CDATA[10000]]></coupon_id>
     *      <coupon_fee><![CDATA[100]]></coupon_fee>
     *      <trade_type><![CDATA[JSAPI]]></trade_type>
     *      <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
     *  </xml>
     * @return string xml
     * @throws Exception
     */
    public function wechat(): string
    {
        $returnStatus = ['return_code' => 'FAIL', 'return_msg' => '签名失败'];

        $xml = file_get_contents('php://input');

//        \think\Log::write('微信支付回调参数' . var_export($xml, true), 'log', true);
        //检验xml格式
        $xml_parser = xml_parser_create();
        if (!xml_parse($xml_parser, $xml, true))
        {
            $data = [];
        } else
        {
            $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        }
        // \think\Log::write('微信支付回调参数' . var_export($data, true), 'log', true);

        //验签名。默认支持MD5
        //获取订单支付账号配置
        $accountConfig = OrdersLibCacheModel::getOrderAccountType($data['out_trade_no'], 2);
        $wxpayConfig = OrdersLib::getPayConfig('wx', $accountConfig['account']);

        $wxConfig = null;
        if (in_array($data['trade_type'], ['JSAPI', 'MWEB'], true))
        {//如果是JSAPI支付方式，那么过滤appid
            foreach ($this->config[$data['trade_type']] as $v)
            {
                if (!isset($wxpayConfig[$v]))
                {
                    continue;
                }
                if ($wxpayConfig[$v]['appid'] == $data['appid'] && $wxpayConfig[$v]['mchid'] == $data['mch_id'])
                {
                    $wxConfig = $wxpayConfig[$v];
                    continue;
                }
            }
        } else
        {
            $wxConfig = $wxpayConfig[$this->config[$data['trade_type']]];
        }

        if (!empty($data) && (new PayCheckSign)->weixin($data, $wxConfig['api_key']))
        {
            if ($data['return_code'] === 'SUCCESS'
                && $data['result_code'] === 'SUCCESS'
                && $data['appid'] === $wxConfig['appid']
                && $data['mch_id'] === $wxConfig['mchid'])
            {
                $out_trade_no = $data['out_trade_no'];// 订单号
                $total_fee = $data['total_fee'] / 100;// 订单总金额 单位为分

                // 回调逻辑处理
                $dbStatus = $this->notify_handle($out_trade_no, $total_fee, 2);
                if ($dbStatus)
                {
                    $returnStatus = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK',
                    ];
                }
                #神策打点
                (new Orders())->getSensorsTrackData($out_trade_no, 'buy_success');
            }
        } else
        {
            Log::write(var_export($xml, true), 'log', true);
            Log::write(var_export($wxConfig, true), 'log', true);
            return false;
        }
        return $this->arrayToXml($returnStatus);
    }

    /**
     * 支付宝支付回调修改订单状态
     * notify_time 通知时间 Date 是 通知的发送时间。格式为yyyy-MM-dd HH:mm:ss 2015-14-27 15:45:58
     * notify_type 通知类型 String(64) 是 通知的类型 trade_status_sync
     * notify_id 通知校验ID String(128) 是 通知校验ID ac05099524730693a8b330c5ecf72da9786
     * app_id 支付宝分配给开发者的应用Id String(32) 是 支付宝分配给开发者的应用Id 2014072300007148
     * charset 编码格式 String(10) 是 编码格式，如utf-8、gbk、gb2312等 utf-8
     * version 接口版本 String(3) 是 调用的接口版本，固定为：1.0 1.0
     * sign_type 签名类型 String(10) 是 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2 RSA2
     * sign 签名 String(256) 是 请参考异步返回结果的验签 601510b7970e52cc63db0f44997cf70e
     * trade_no 支付宝交易号 String(64) 是 支付宝交易凭证号 2013112011001004330000121536
     * out_trade_no 商户订单号 String(64) 是 原支付请求的商户订单号 6823789339978248
     * trade_status 交易状态 String(32) 否 交易目前所处的状态，见交易状态说明 TRADE_CLOSED
     *      WAIT_BUYER_PAY 交易创建，等待买家付款 || TRADE_CLOSED  未付款交易超时关闭，或支付完成后全额退款 || TRADE_SUCCESS   交易支付成功 || TRADE_FINISHED     交易结束，不可退款
     * @throws Exception
     */
    public function ali(): void
    {
        $param = input('param.');

        // \think\Log::write('支付宝支付回调参数:' . var_export($param, true), 'log', true);

        $returnStatus = 'fail';
        //获取订单账号类型
        $accountConfig = OrdersLibCacheModel::getOrderAccountType($param['out_trade_no'], 1);
        $aliConfig = OrdersLib::getPayConfig('ali', $accountConfig['account']);
        // 签名成功
        if ((new PayCheckSign)->ali($_POST, $aliConfig))
        {
            $trade_status = $param['trade_status'] ?? '';

            if ($trade_status === 'TRADE_SUCCESS')
            {
                //===============如果支付成功，修改订单状态===========================//
                $out_trade_no = $param['out_trade_no'] ?? '';//获取订单号
                $app_id = $param['app_id'] ?? '';
                $seller_email = $param['seller_email'] ?? '';
                $seller_id = $param['seller_id'] ?? '';
                $total_amount = $param['total_amount'] ?? '';

                if (
                    $app_id === $aliConfig['app_id']
                    && $seller_email === $aliConfig['seller_email']
                    && $seller_id === $aliConfig['seller_id']
                )
                {
                    // 回调逻辑处理
                    $dbStatus = $this->notify_handle($out_trade_no, $total_amount, 1);
                    if ($dbStatus)
                    {
                        $returnStatus = 'success';
                    }
                    #神策打点
                    (new Orders())->getSensorsTrackData($out_trade_no, 'buy_success');
                }
            }
        }
        echo $returnStatus;
        exit;
    }


    /**
     * 私域实物商品销售 微信支付成功以后的回调
     *  <xml>
     *      <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
     *      <attach><![CDATA[支付测试]]></attach>
     *      <bank_type><![CDATA[CFT]]></bank_type>
     *      <fee_type><![CDATA[CNY]]></fee_type>
     *      <is_subscribe><![CDATA[Y]]></is_subscribe>
     *      <mch_id><![CDATA[10000100]]></mch_id>
     *      <nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
     *      <openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
     *      <out_trade_no><![CDATA[1409811653]]></out_trade_no>
     *      <result_code><![CDATA[SUCCESS]]></result_code>
     *      <return_code><![CDATA[SUCCESS]]></return_code>
     *      <sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
     *      <sub_mch_id><![CDATA[10000100]]></sub_mch_id>
     *      <time_end><![CDATA[20140903131540]]></time_end>
     *      <total_fee>1</total_fee><coupon_fee><![CDATA[10]]></coupon_fee>
     *      <coupon_count><![CDATA[1]]></coupon_count>
     *      <coupon_type><![CDATA[CASH]]></coupon_type>
     *      <coupon_id><![CDATA[10000]]></coupon_id>
     *      <coupon_fee><![CDATA[100]]></coupon_fee>
     *      <trade_type><![CDATA[JSAPI]]></trade_type>
     *      <transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
     *  </xml>
     * @return string xml
     * @throws Exception
     */
    public function pri_wechat()
    {
        $returnStatus = ['return_code' => 'FAIL', 'return_msg' => '签名失败'];

        $xml = file_get_contents('php://input');

//        \think\Log::write('微信支付回调参数' . var_export($xml, true), 'log', true);
        //检验xml格式
        $xml_parser = xml_parser_create();
        if (!xml_parse($xml_parser, $xml, true))
        {
            $data = [];
        } else
        {
            $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        }

        // \think\Log::write('微信支付回调参数' . var_export($data, true), 'log', true);
        // 订单编号
        $outTradeNo = $data['out_trade_no'];
        $privateAreaOrderModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrderModel->getInfoById($outTradeNo);
        if (!$orderInfo)
        {
            return $this->arrayToXml($returnStatus);
        }
        $extend = $orderInfo['extend'] ? json_decode($orderInfo['extend'], true) : [];
        // 获取公司信息
        $privateAreaMallCompanyModel = new PrivateAreaMallCompany();
        $companyData = $privateAreaMallCompanyModel->getInfoById($extend['mall']['cid']);
        //获取支付配置信息
        $wxConfig = $privateAreaMallCompanyModel->getCompanyPayConfig($companyData, 2);

        if (!empty($data) && (new PayCheckSign)->weixin($data, $wxConfig['api_key']))
        {
            if ($data['return_code'] === 'SUCCESS'
                && $data['result_code'] === 'SUCCESS'
                && $data['appid'] === $wxConfig['appid']
                && $data['mch_id'] === $wxConfig['mchid'])
            {
                $out_trade_no = $data['out_trade_no'];// 订单号
                $total_fee = $data['total_fee'] / 100;// 订单总金额 单位为分

                // 回调逻辑处理
                $dbStatus = $this->notify_handle($out_trade_no, $total_fee, 2);
                if ($dbStatus)
                {
                    $returnStatus = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK',
                    ];
                }
                #神策打点
                (new Orders())->getSensorsTrackData($out_trade_no, 'buy_success');
            }
        } else
        {
            Log::write(var_export($xml, true), 'log', true);
            Log::write(var_export($wxConfig, true), 'log', true);
            return false;
        }
        return $this->arrayToXml($returnStatus);
    }

    /**
     * 私域实物商品销售 支付宝支付回调修改订单状态
     * notify_time 通知时间 Date 是 通知的发送时间。格式为yyyy-MM-dd HH:mm:ss 2015-14-27 15:45:58
     * notify_type 通知类型 String(64) 是 通知的类型 trade_status_sync
     * notify_id 通知校验ID String(128) 是 通知校验ID ac05099524730693a8b330c5ecf72da9786
     * app_id 支付宝分配给开发者的应用Id String(32) 是 支付宝分配给开发者的应用Id 2014072300007148
     * charset 编码格式 String(10) 是 编码格式，如utf-8、gbk、gb2312等 utf-8
     * version 接口版本 String(3) 是 调用的接口版本，固定为：1.0 1.0
     * sign_type 签名类型 String(10) 是 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2 RSA2
     * sign 签名 String(256) 是 请参考异步返回结果的验签 601510b7970e52cc63db0f44997cf70e
     * trade_no 支付宝交易号 String(64) 是 支付宝交易凭证号 2013112011001004330000121536
     * out_trade_no 商户订单号 String(64) 是 原支付请求的商户订单号 6823789339978248
     * trade_status 交易状态 String(32) 否 交易目前所处的状态，见交易状态说明 TRADE_CLOSED
     *      WAIT_BUYER_PAY 交易创建，等待买家付款 || TRADE_CLOSED  未付款交易超时关闭，或支付完成后全额退款 || TRADE_SUCCESS   交易支付成功 || TRADE_FINISHED     交易结束，不可退款
     * @throws Exception
     */
    public function pri_ali(): void
    {
        $param = input('param.');

        $returnStatus = 'fail';
        // 订单编号
        $outTradeNo = $param['out_trade_no'];
        $privateAreaOrderModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrderModel->getInfoById($outTradeNo);
        if (!$orderInfo)
        {
            return;
        }
        $extend = $orderInfo['extend'] ? json_decode($orderInfo['extend'], true) : [];
        // 获取公司信息
        $privateAreaMallCompanyModel = new PrivateAreaMallCompany();
        $companyData = $privateAreaMallCompanyModel->getInfoById($extend['mall']['cid']);
        $payConfig = $privateAreaMallCompanyModel->getCompanyPayConfig($companyData, 1);
        // 签名成功
        if ((new PayCheckSign)->ali($_POST, $payConfig))
        {
            $trade_status = $param['trade_status'] ?? '';

            if ($trade_status === 'TRADE_SUCCESS')
            {
                //===============如果支付成功，修改订单状态===========================//
                $out_trade_no = $param['out_trade_no'] ?? '';//获取订单号
                $app_id = $param['app_id'] ?? '';
                $seller_email = $param['seller_email'] ?? '';
                $seller_id = $param['seller_id'] ?? '';
                $total_amount = $param['total_amount'] ?? '';

                if (
                    $app_id === $payConfig['app_id']
                    && $seller_id === $payConfig['seller_id']
                )
                {
                    // 回调逻辑处理
                    $dbStatus = $this->notify_handle($out_trade_no, $total_amount, 1);
                    if ($dbStatus)
                    {
                        $returnStatus = 'success';
                    }
                    #神策打点
                    (new Orders())->getSensorsTrackData($out_trade_no, 'buy_success');
                }
            }
        }
        echo $returnStatus;
        exit;
    }

    /**
     * 京东支付回调
     * demo xml
     * <?xml version="1.0" encoding="UTF-8" ?><jdpay>  <version>V2.0</version>  <merchant>110148035005</merchant>  <result>    <code>000000</code>    <desc>success</desc>  </result>  <encrypt>M2JlZTE1NTZkMTdmOGYzN2ZkN2YyY2IwNTFkMTI0MzgwYTA5ZjAxM2ZhNWI5NmUyNjVmNzg5ZmIyY2E4OWJkMmM5N2VmYWVlMDViMzJhNWQwYWVhZDI4YTE5MjRhY2QzZjAyZmMxMjcyODVhNjM4ZWE3ZDkxNjk1N2VlYTVlMTQ0MzMzNWFlODg2MzAzOTE1ZDQyNDM3NzlmZmM2NzA1NjNmNTA2MGVjZjRmOWFlZjVkZDNkZjM2NjZlYTU4Mjk1NDZjOTUxMmJkOTI4NzM0MjBjMWUyMjU2Njg5ZjNmMjNhZjU4Njg2YWJjNDEwOWEyOGU2ZjZmMzkyZDIwNDM5ZjQxMTc0NzdiYjRmMjA3MWQxMjRlYTA0YmJlMWI1OTFjZGM5YWE1YTU5MDQ5MmQ0ZWE5NDdlNTNhNTBjZGZjNWQ2M2MyNWRlN2VhNzJhOWVlODg3ZmYzZmJjNzNlMWI1YzExYzk1MWRiNjhlY2QwOGFmZWZlYmEwNTk1NmU3MDI0NDEzY2E0NjdlNjkzNDViNWEzOTY4ZGM4M2Y0ZDk1ZGI4YWRiM2FlMjlmNGMyNDRjNjIwMTBmOWUxOTUwYjQ3ODg3OGQyYzAwZWUzY2U0ZGViMDMxZGE5YjlhMTZhNWRhMjdkNTRlMWQxNjExYjUwZGVkNzZkMGZmNWQ0YTg1ODFkN2NjNTEzODYyMGQ5OGYwZDlhODJmMTE4YWRlZTM1YzgwNDAxYTcwNzY1ZDNmY2ZkNTdjNGY4NzNhMzhhZTA4OWFmMDAxMTMyYWNmZjM0NTdhZDczYjhkOTJhNGIxMzMxNzQ3ZTMwYmQ4Njg2MGRkMDEwOGM0ZmNkMzU4M2I4YjI1NDdiMjU0OTdmZjNkMTYyZTU5MzFlODNkN2ZjZmZjYjhjYzUxNjY1NGMwMjA0MDk3YTNiNDM0YzFlNDdkZDU1ODZkN2ZlMTBkNWNkNWRmOGYyOWQ0NTk2MmMxMGYzYTE1MTJhNDM5M2M5YWI0ZmQ4MmYwYjFjMzRlNDJiMGJkNDY3YWFjMGU0OGI2YTJkMmUzZDA3ZWIxNmJmM2I5NWViNzk1MzEwZTBhNDUyZjdkYTMzMjhhNWVlZjJkN2M0MjUxZWRjY2ZmNDY2OTI1NjdlMGExMThkNjkyNGNkMGYzZjllYjEwZTAzYmMzMGZmMmQ0NDBjZGVkOWJkZGRjNjdkZmJlYjZjY2ExODk1Zjc3ZjQzNDZhMDdlNmM5M2ZlOWVjZTFkY2IyMDk2ODcwODhhMzM3ZTJhYTMzNWQyMjE4ZmIwZmUyNWYyYTFiYzc3MDgxNjZmYWM3ODJjOGQwYTc1NmQ2NmFmNDhmYjEzNTIwYzhmYjIxYjgzYmY4ZGRlYTI3MTA4YjAzZDA0OWJlYjUwZmQ1YTU5OTE0MzIwMWMxOTM4OTk4OWRjYjVmMmFkNWU4OGFmZGM2YmJlZmFjYjVhNDE1NGZmYjRmNWNjYmE3YWYwNzcxMDUxODU4NTM3YzdiNzhmYWUyNmE4ZDFjZmIzMjRiN2I4ZGZlNTE2NzBlZTUyMDA1Y2Y4Mjg4MzhkOTAwMDYxNGIyNTExZTZhNDM2Yzg1NmZhODY2YWE1YzFjY2E1Y2NkNjVkYmNiY2IzYTFiZmM4OWY1NGVlOWNjMzhmM2U3MThlYTFhMGYwMTJjNzAwMGU4MzlmZDdhOTc0MDdlY2FiODVkMGVhOTc2MDg4NWU4YjJlYjM2MTAzMmQ1ZDc4N2FhY2Q5NWQ1NmIxMjkzMGMwY2EyZDhkZmFiZmI2NWI0MDEyNmJmZDRjZGNlNDgyNjg5ZmMzNzJiOThmNzdjNzE5NWJjZTZkYTY2MzYxZjY1OTdmZTM0YjhhMDYzNDQwYmM2Y2MwZTYyZjM0NzEyYmJmZDhjN2MwZTM2Zjk0NDBiYzZjYzBlNjJmMzQ3NGFmNDY5YTg5MDFjYzA4MzVjYmUyYTMzMmI2YWEwYWJhN2Y4NjVjMjg2NzNiYzA0YjlmZGRjNTFlMDNmMDkzNjhiMmJkNTVjZmFhZDM4M2MzZjA1MTA2NGMzOWUzZTQwYzczNjRjNmE3NWI4OTNmZThmMTM5ZTRkMDE2YjJkMDVmNTdmZTg0YWI2OGZkMDYyNjlmZWRmYzYyYTg0YzM0YzgxNzRkYjI2ZGFlOGExYTlmN2JjNjIzNjUxNGI5MDhmZTQyYjM0ODE1MjRlYWIwMmIzOTNlOTk0OWZlYzFmZmE4YzBkNTU5MDQwMGRiNTE0ODI0ZjBhMWQyZDAxMWExM2M1ZDUxZDhiNzRhMTg4YWY=</encrypt></jdpay>
     * @throws Exception
     */
    public function jd()
    {
        $xml = file_get_contents('php://input');

//        \think\Log::write('京东支付回调参数' . var_export($xml, true), 'log', true);

        $returnStatus = 'fail';
        $jdConfig = OrdersLib::getPayConfig('jd');

        if ((new PayCheckSign)->jd($xml, $data, $jdConfig))
        {
            /**
             * merchant 商户号
             * status  交易状态 2-成功
             * tradeType 交易类型 0-消费，1-退款
             * amount 支付总金额 商户订单的资金总额。单位：分，大于0
             * payType 支付方式 0-银行卡,1-白条,2-余额,3-优惠券,5-小金库,6-钢镚,8-白条分期,9-白条支付（不分期)
             * currency 交易币种 货币类型，固定填CNY
             * tradeTime 交易时间 订单生成时间。格式：“yyyyMMddHHmmss”
             */
            if ($data['result']['code'] === '000000' && $data['result']['desc'] === 'success'
                && $data['merchant'] === $jdConfig['merchant'] && $data['status'] == 2
                && $data['tradeType'] == 0)
            {
                $out_trade_no = $data['tradeNum'];// 订单号
                $total_amount = (int)$data['amount'] / 100;// 订单总金额 单位为分
                // 回调逻辑处理
                $dbStatus = $this->notify_handle($out_trade_no, $total_amount);
                if ($dbStatus)
                {
                    $returnStatus = 'ok';
                }
            }
        }
        echo $returnStatus;
        exit;
    }

    /**
     * 回调后的逻辑处理
     * @param $order_id
     * @param $total_amount
     * @param $tradeType
     * @return bool
     */
    private function notify_handle($order_id, $total_amount, $tradeType): bool
    {
        return (new Orders())->notify_handle($order_id, $total_amount, $tradeType);
    }

    /**
     * 数组转xml
     * @param $arr
     * @return string
     */
    private function arrayToXml($arr): string
    {
        $xml = '<xml>';
        foreach ($arr as $key => $val)
        {
            if (is_numeric($val))
            {
                $xml .= '<' . $key . '>' . $val . '</' . $key . '>';

            } else
            {
                $xml .= '<' . $key . '><![CDATA[' . $val . ']]></' . $key . '>';
            }
        }
        $xml .= '</xml>';
        return $xml;
    }
}
